#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice
import sys, os, thread

try:
    HOME = os.environ['FIPA']
except KeyError:
    print 'FIPA environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(HOME, 'test', 'Spammer.ice')
Ice.loadSlice('--all -I/usr/share/Ice/slice', ['-I' + SLICE, FILE])

import FIPA
import Test
import SpammerI
from SpammerI import *

class SpammerFactoryI (FIPA.AgentFactory):

    def __init__ (self):
        # Key   ==> Object identity.
        # Value ==> Servant.
        self.__agents = {}
        self.__mutex = thread.allocate_lock()

    # Create and individual agent identified by name.
    # if name == '', then generate a new identity.
    # Return the agent's proxy.
    def create (self, name, curr):
        self.__mutex.acquire()

        # Create the ID.
        if name == '':
            id = curr.adapter.getCommunicator().stringToIdentity(Ice.generateUUID())
        else:
            id = curr.adapter.getCommunicator().stringToIdentity(name)

        # Register the servant.
        try:
            servant = SpammerI(id, curr.adapter)
            prx = Test.SpammerPrx.uncheckedCast(curr.adapter.add(servant, id))
            self.__agents[id] = servant
        except Ice.AlreadyRegisteredException:
            self.__mutex.release()
            raise FIPA.AgentExists

        # Check if some agent was destroyed.
        # TODO: all in a simple loop.
        ids = []
        for id, servant in self.__agents.iteritems():
            if servant.isZombie():
                ids.append(id)
        for id in ids:
            self.__agents.pop(id)
            
        # Return the agent's proxy.
        self.__mutex.release()
        return prx

    # Create a set of agents identified by names.
    # Return a tuple with the proxies and the names already registered.
    def createSeq (self, names, curr):
        self.__mutex.acquire()
        prxs = []
        namesAlreadyRegistered = []

        for name in names:
            # Create the ID.
            if name == '':
                id = curr.adapter.getCommunicator().stringToIdentity(Ice.generateUUID())
            else:
                id = curr.adapter.getCommunicator().stringToIdentity(name)

            # Register the servant.
            try:
                servant = SpammerI(id, curr.adapter)
                prxs.append(Test.SpammerPrx.uncheckedCast(curr.adapter.add(servant, id)))
                self.__agents[id] = servant
            except Ice.AlreadyRegisteredException:
                namesAlreadyRegistered.append(name)

        # TODO: all in a simple loop.
        ids = []
        for id, servant in self.__agents.iteritems():
            if servant.isZombie():
                ids.append(id)
        for id in ids:
            self.__agents.pop(id)

        self.__mutex.release()
        return prxs, namesAlreadyRegistered
